package solution._0040._0047;

import java.util.*;

/**
 * Created by chen_snow
 * Date: 2021/6/2 23:50
 * Description: 全排列 II
 */
public class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        boolean[] flags = new boolean[nums.length];
        backTrace(nums, new ArrayDeque<>(), flags, result);
        return result;
    }

    public void backTrace(int[] nums, Deque<Integer> data, boolean[] flags, List<List<Integer>> result) {
        if (data.size() == nums.length) {
            result.add(new ArrayList<>(data));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (flags[i] || (i > 0 && nums[i] == nums[i - 1] && !flags[i - 1])) {
                continue;
            }

            data.addLast(nums[i]);
            flags[i] = true;
            backTrace(nums, data, flags, result);
            data.removeLast();
            flags[i] = false;
        }
    }
}
